/*
 * @Descripttion: GGB
 * @version: 1.0
 * @Author: GGB
 * @Date: 2022-01-30 11:57:42
 * @LastEditors: GGB
 * @LastEditTime: 2022-01-31 12:17:50
 */
const { ipcRenderer } = require('electron')
const { dialog, getCurrentWindow } = window.require('@electron/remote')
const Store = require('electron-store')
const settingsStore = new Store({ name: 'Settings' })
const qiniuConfigArr = ['#savedFileLocation', '#accessKey', '#secretKey', '#bucketName']

const $ = (selector) => {
  const result = document.querySelectorAll(selector)
  return result.length > 1 ? result : result[0]
  // return document.getElementById(id)
}

// document.addEventListener('DOMContentLoaded', () => {
//   let savedLocation = settingsStore.get('savedFileLocation')
//   if (savedLocation) {
//     $('#savedFileLocation').value = savedLocation
//   }
//   $('#select-new-location').addEventListener('click', () => {
//     dialog.showOpenDialog({
//       properties: ['openDirectory'],
//       message: '选择文件的存储路径',
//     }).then(result => {
//       const { canceled, filePaths } = result
//      console.log(filePaths[0])
//       if (canceled||!filePaths.length) return
//       $('#savedFileLocation').value = filePaths[0]
//         savedLocation=filePaths[0]
//     }).catch(err => {
//       console.log(err)
//     })
//   })
//   $('#settings-form').addEventListener('submit', () => {
//     settingsStore.set('savedFileLocation', savedLocation)
//     getCurrentWindow().close()
//   })
// })

document.addEventListener('DOMContentLoaded', () => {
  let savedLocation = settingsStore.get('savedFileLocation')
  if (savedLocation) {
    $('#savedFileLocation').value = savedLocation
  }
  // get the saved config data and fill in the inputs
  qiniuConfigArr.forEach(selector => {
    const savedValue = settingsStore.get(selector.replace('#',''))
    if (savedValue) {
      $(selector).value = savedValue
    }
  })
  $('#select-new-location').addEventListener('click', () => {
   dialog.showOpenDialog({
      properties: ['openDirectory'],
      message: '选择文件的存储路径',
    }, (path) => {
      if (Array.isArray(path)) {
        $('#savedFileLocation').value = path[0]
      }
    })
  })
  $('#settings-form').addEventListener('submit', (e) => {
    e.preventDefault()
    qiniuConfigArr.forEach(selector => {
      if ($(selector)) {
        let { id, value } = $(selector)
        settingsStore.set(id, value ? value : '')
      }
    })
    // sent a event back to main process to enable menu items if qiniu is configed
    ipcRenderer.send('config-is-saved')
    getCurrentWindow().close()
  })
  $('.nav-tabs').addEventListener('click', (e) => {
    e.preventDefault()
    $('.nav-link').forEach(element => {
      element.classList.remove('active')
    })
    e.target.classList.add('active')
    $('.config-area').forEach(element => {
      element.style.display = 'none'
    })
    $(e.target.dataset.tab).style.display = 'block'
  })
})